﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Web.Script.Serialization;
using System.Net.Http.Headers;

namespace PowerBooking.RSE.ConsoleTest
{
    /// <summary>
    /// Http请求类
    /// </summary>
    public class HttpHelper
    {
        private static JavaScriptSerializer JsonSerialize = new JavaScriptSerializer();

        /// <summary>
        /// Get方法
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <returns></returns>
        public static Tuple<T, HttpStatusCode> Get<T>(string url)
        {
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync(url);
                response.Wait();
                var jsonStr = response.Result.Content.ReadAsStringAsync();
                jsonStr.Wait();
                return new Tuple<T, HttpStatusCode>(JsonSerialize.Deserialize<T>(jsonStr.Result), response.Result.StatusCode);
            }
        }

        /// <summary>
        /// Post方法
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="obj">实体</param>
        /// <returns></returns>
        public static Tuple<T, HttpStatusCode> Post<T>(string url, object obj)
        {
            using (var httpClient = new HttpClient())
            {
                var content = new StringContent(JsonSerialize.Serialize(obj));
                var response = httpClient.PostAsync(url, content);
                response.Wait();
                var jsonStr = response.Result.Content.ReadAsStringAsync();
                jsonStr.Wait();
                return new Tuple<T, HttpStatusCode>(JsonSerialize.Deserialize<T>(jsonStr.Result), response.Result.StatusCode);
            }
        }

        /// <summary>
        /// Post方法
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="obj">实体</param>
        /// <returns></returns>
        public static HttpStatusCode Post(string url, object obj)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
                request.Content = new StringContent(JsonSerialize.Serialize(obj), Encoding.UTF8, "application/json");
                var resposne = httpClient.SendAsync(request);
                resposne.Wait();
                return resposne.Result.StatusCode;
            }
        }
    }
}
